home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Apple Developer Connection Student Program
/
ADC Tools Sampler CD Disk 3 1999.iso
/
Documentation
/
Books
/
Learn Java on the Macintosh
/
Learn Java Projects
/
14.02 - next prime
/
NextPrime.java
next >
Wrap
Text File
|
1996-04-22
|
2KB
|
58 lines
/* -------------------------------------------------------------
This stand-alone application finds the next prime after the
integer passed to it as a command line parameter.
Java's classes: Applet (applet)
Exception (lang)
String (lang)
Integer (lang)
Math (lang) to find the square root
Custom classes: NextPrime
------------------------------------------------------------- */
public class NextPrime {
public static void main(String[] args) {
int startingPoint, candidate, last, i;
boolean isPrime;
if (args.length == 1) {
try {
Integer integer = new Integer(args[0]);
startingPoint = integer.intValue();
} catch (Exception e) {
return;
}
} else
return;
if ( startingPoint < 2 ) {
candidate = 2;
} else if ( startingPoint == 2 ) {
candidate = 3;
} else {
candidate = startingPoint;
if (candidate % 2 == 0) /* Test only odd numbers */
candidate--;
do {
isPrime = true; /* Assume glorious success */
candidate += 2; /* Bump to the next number to test */
last = (int)Math.sqrt( candidate ); /* We'll check to see if candidate */
/* has any factors, from 2 to last */
/* Loop through odd numbers only */
for ( i = 3; (i <= last) && isPrime; i += 2 ) {
if ( (candidate % i) == 0 )
isPrime = false;
}
} while ( ! isPrime );
}
System.out.println( "The next prime after " + startingPoint + " is " + candidate);
}
}